package com.ilovepostcard.view;

import com.ilovepostcard.R;
import com.ilovepostcard.controller.ServerAsyncTask;
import com.ilovepostcard.controller.server.PostcardResult;
import com.ilovepostcard.controller.server.ServerFactory;
import com.ilovepostcard.model.SimpleUser;
import com.ilovepostcard.utils.DrawableManager;
import com.ilovepostcard.utils.UserHeaderUrlCache;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

public class UserWidget extends RelativeLayout {

    SimpleUser simpleUser;
    ImageView user_widget_head;
    
    public UserWidget(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        inflate();
    }

    public UserWidget(Context context, AttributeSet attrs) {
        super(context, attrs);
        inflate();
    }

    public UserWidget(Context context) {
        super(context);
        inflate();
    }
    
    public void setSimpleUser(final SimpleUser user) {
        simpleUser = user;
        String headUrl = UserHeaderUrlCache.get(simpleUser.UserID);
        if (headUrl != null) {
            setupHeadImage(headUrl);
        } else {
            user_widget_head.setImageResource(R.drawable.user_defult_100);
            new ServerAsyncTask(getContext()) {
                
                protected boolean isShowDialog() {
                    return false;
                }
                
                @Override
                protected void onSuccess(PostcardResult result) {
                    String url = result.getUserHeadImgUrl();
                    UserHeaderUrlCache.put(simpleUser.UserID, url);
                    setupHeadImage(url);
                }
                
                @Override
                protected PostcardResult doRequest() {
                    return ServerFactory.getServer().getUserHeadImg(simpleUser.UserID);
                }
            }.execute();
        }
    }
    
    private void setupHeadImage(String url) {
        if (!DrawableManager.getInstance().fetchDrawableOnThread(url, user_widget_head))
            user_widget_head.setImageResource(R.drawable.user_defult_100);
    }

    private void inflate() {
        View view = View.inflate(getContext(), R.layout.user_widget, this);
        user_widget_head = (ImageView) view.findViewById(R.id.user_widget_head);
    }
}
